Function
Function <.FuncName.>[(ParamList)] ... [ExitFunction] ... EndFunction
 
Parameters: NONE
Returns: NONE
 

     User Defined Functions are a way users can create their own commands. These are often used to help simplify or remove repetitive sections of code from our programs. This can have many benefits, such as it can helps reduce the size of our program, and it lets us reuse common pieces of code. It's not uncommon for programmers to reuse previously written functions between different projects. Further accelerating the development of new programs. So if you find yourself writing the same bits of code, over and over again. Then you might well be in need of Functions.


      A function can be declared in any part of your program. Many programmers tend to place them at the bottom of their code, some at the top. While this is generally personal preference, it is sometimes necessary to place them at the bottom, due to some dependency in the function code, such as, the function operates upon a typed array for example. Which would need to be declared before the function appears in the your code.


      So what actually is a function ? - Well, we can think of it as a piece of code that has a specific entry and exit point. The only way to execute the code inside a function, is by explicitly calling it.


      When calling a function, we'll need to pass whatever input parameters it requires. You can think if this as seeding the input parameters to their starting values. Upon doing this PlayBASIC jumps to execute the code inside the function, only returning when the code is complete. When PB returns from a function call, it returns us back to the point from which the function was originally called. Much like the Gosub/Return mechanism, except a little more advanced.


      The main differences would be that each time we call a function, the variables inside it are initialized to zero. So each time we use a function, it's always starting in a fresh state. Another big difference, is that we can both pass information explicitly to the function (for it operate upon) and retrieve any results from it. The latter is probably the most common usage initially, where we might roll some repetitive code, such as some math calculation into our own function. Then rather than use the long winded math calculation throughout our code, over and over again, we'd just call our custom function.


      Another difference about functions is that any variables or arrays created within the function are Local to that function. This means they only exist and are visible inside the walls of the function, and can not be accessed externally, which is often called Scope. This behavior avoids the potential variable name collision problems, that programmers tend to run into when using lots of sub-routines (Gosub / Return). Which occurs when a programmer re-uses a variable name for something different in a sub routine (or some other part of code), which can introduce some unwanted behavior to a program. These types of cascading errors can be very difficult to track down in large programs.


      Initially local scope is a big stumbling block for many new programmers to come to terms with though, who often find this very restrictive, and they'd be right, it is. But that's the purpose of functions, they're meant to be tightly packed stand alone mini programs. Because of this, it's harder for us to make silly re-use style errors in our programs, plus they can shared between projects. However, they're not totally cut off from the rest of the program, as the code inside the function can access other Global Variables & Arrays and of course other functions.



I N D E X:







Function Declaration:


     Okay let's start by writing a basic function to print "Hello" on the screen (do not run it yet):

  
Function Show_Text()
  Text 10,10,"Hello"
EndFunction
  


     As you can see the function itself can be divided into 3 separate parts. For ease we'll refer to them as the header, the code sequence and the footer:



FUNCTION Show_Text() -the header
TEXT 10,10,"Hello" -the code sequence
ENDFUNCTION -the footer



     The Header - This consists of the command followed by the name of our function, in this case Show_Text followed by a set of brackets (more on these later).

     The Code Sequence - Here we put all the code we want to be run when we call the function from within our program. Here it's TEXT 10,10,"Hello"

     The Footer - Here the ENDFUNCTION command is used to signify the end of our function code sequence. The ENDFUNCTIONcommand can be followed also by a variable but again more on that later.

     Now just typing that function into the editor and running it will do nothing. All commands between the and ENDFUNCTION commands are ignored until you add a function call to your program. A function call is added by simply typing the name of the required function. So let's add that along with a WAITKEY command so we can see the result of our function:

  
  Show_Text()
  WaitKey
  
Function Show_Text()
  Text 10,10,"Hello"
  Sync
EndFunction
  


     So now try running that in the editor. Not terribly impressive so far but that's the very basics of functions covered. Simple enough isn't it.

Note: Need more information on functions ? See the Functions&Psub tutorial.


Top





Input Parameters:


      In the header of a User defined function, you can declare a list of Variables, Arrays, Types and even Lists that this function requires the user pass it. These parameters will be information that the uses passes to the function, which in turn it uses to perform whatever calculation that is it does.

      So for example, a function that Adds two numbers together and displays the result, would need two input parameters, those being the two variables. Lets assume we want to add two integers together, so our code might look something like this.

Example,

  
Function Add(Value1 , Value2)
  Print Value1 +Value2
EndFunction
  



      If you look carefully, you'll see that the variables we've named as our Add Functions input parameters (Value1 and Value2) are the one's our operations are using inside the function also. These variables are only visible (and only exist) inside the function. These are known as Local Varibales.

      When we call a function, whatever variables/information we send to the function, is internally passed into the Functions input parameters.



Usage Example,

  
; Call our Add function, passing two constants into it.
  Add(100,200)
  
; call our Add function, but this time send the values in
; some variables into the function.
  A=100
  b=200
  Add(A,B)
  
  Sync
  WaitKey
  
Function Add(Value1 , Value2)
  Print Value1 +Value2
EndFunction
  


Top





Return Parameters:


      Often functions will need to return information back to the user, since our function is performing some type of calculation for us. The returned information returned is declared after the functions closing EndFunction statement. Generally we'll be returning Variables, but you can also return Arrays even Types from functions.

      In this example, we're going to define a function that will add two integer values togeter, then return the answer back to us. As you can see in the example bellow, we've called our function Add and this functions accepts to integer variables as input parameters, as well as returning the answer in an integer variable called result. The code between the Function/EndFunction statements performs the required calculation, in this case we want it to add the input parameters together, then store the answer in the result variable..


Example,

  
Function Add(Value1 , Value2)
  Result= Value1 + Value2
EndFunction  Result
  




Usage Example:


  
  Print Add(100,50)
  Print Add(200,100)
  Sync
  WaitKey
Function Add(Value1 , Value2)
  Result= Value1 +Value2
EndFunction  Result
  


If we run this example in the editor it'll display 150, then 300 on the next row.

Top





Input/Return Parameter Declaration Syntax


      So what about the syntax of function input and return parameters ?, Well in the above examples we've declared our two integer variables using the short hand form.

      Short hand ? Parameters and variables declarations can be generally be declared in two ways. The first is the implied method (short hand), which means that when PlayBASIC sees a variable (or array) it'll use the post fix symbol to determine it's type. The other method, is the long hand form using the AS DataType notation. The long hand notation lets us be much more specific about what type of information this parameter is.


Accepted (As DataType) Declarations


Variables:

Variable as Integer (Declare Variable as Integer)
Variable as Float (Declare Variable as Float)
Variable as String (Declare Variable as String)


Types:
Ptr as UserDefinedType (Declare Ptr as individual Type buffer.)



Arrays :

Array() as integer (Declare Integer Array)
Array() as float (Declare Float Array )
Array() as string (Declare String Array )
Array() as UserDefinedType (Declare UserDefined Type Array )



linked List:


Array as UserDefinedType List (Declare UserDefined Type List List/Variable/Array Container)



Pointers:

Ptr as Pointer (Declare Ptr as generic Pointer)
Ptr as Byte Pointer (Declare Ptr as Pointer)
Ptr as Word Pointer (Declare Ptr as Pointer)
Ptr as Integer Pointer (Declare Ptr as Pointer)
Ptr as Float Pointer (Declare Ptr as Pointer)
Ptr as StringRef Pointer (Declare Ptr as Pointer)
Ptr as UserDefinedType Pointer (Declare Ptr as Pointer)







Accepted Short Hand Declarations


Variables:


Variable (Declare Variable as Integer)
Variable# (Declare Variable as Float)
Variable$ (Declare Variable as String)


Arrays (Containers):

Array() (Declare Integer Array Container)
Array#() (Declare Float Array Container)
Array$() (Declare String Array Container)
Array().UserDefinedType (Declare UserDefined Type Array)
Array.UserDefinedType (Declare UserDefined Type List/Variable/Array)



Sample
  
Function Example1(IntVariable,FltVariable#,StrVariable$)
EndFunction
  
Function Example2(IntVariable As Integer ,FltVariable As Float,StrVariable As String)
EndFunction
  
Function Example3(Array(), Index As Integer)
EndFunction
  
  
  Type Position
     x#,y#
  EndType
  
; This function expects a Typed array as it's input parameter
Function Example4(Array().Position)
EndFunction
  
; This function expects a Typed Variable or List as it's input parameter
Function Example5(Array.Position)
EndFunction
  
; This function expects a Indivual Type Buffer as it's input parameter
Function Example6(Me As Position)
EndFunction
  


Top







FACTS:


* Functions can call themselves recursively.

* Function declaration keywords (Function & EndFunction) can not be indented.

* Values or expressions that follow EndFunction and ExitFunction must be of the same data type.

* Function input/output parameters can be Integer,Float, String, Typed Variables.

* Function input/output parameters can be Integer,Float, String, Arrays and Typed Arrays.

* Functions return multiple values from a function (integer,float,string).

* Need more information on functions ? See the Functions&Psub tutorial. Also, See the ArrayBasics, Types tutorials for passing arrays & types.

Top







Example #1:


  
; Call the Functions
  
; Call a function that doesn't return a result value, or have an input parameters
  NoReturnValue()
  
;
  Print ExitEarly(1)
  Print ExitEarly(5)
  
; call a function that returns 3 pieces of data
  MyLife, MyName$, MyFloatValue# = MoreReturnValues()
  
  Print MyLife
  Print MyName$
  Print MyFloatValue#
  
; Display the Screen and wait for the user to press a key
  Sync
  WaitKey
  
  
; A Function that does use and input parameters or
; Return a value
Function NoReturnValue()
  Print "This function doesn't return anything"
EndFunction
  
  
; A function that conditionally exits based upon
; the value that's passed into it.
Function ExitEarly(AValue)
  If AValue = 5 Then Exitfunction "I exit early"
EndFunction "I exit late"
  
  
; A function that returns three values
Function MoreReturnValues()
  Life = 42
  Name$ = "Deep Thought"
EndFunction Life, Name$, 4.321
  




This example would output.

  
  This Function doesn't Return anything
  I Exit late
  I Exit early
  42
  Deep Thought
  4.321
  


Top







Example #2:


In this example we're returning an Integer array from a function.

  
; declare myarray with zero items in it
  Dim MyArray(0)
  
; call a function that creates an array 10 items
; in size, fills it random values and returns this array
  MyArray() =ReturnIntegerArray(10)
  
  For lp =0 To 10
     Print MyArray(lp)
  Next
  
; Display the Screen and wait for the user to press a key
  Sync
  WaitKey
  
  
Function ReturnIntegerArray(Size)
  Dim Me(Size)
  For lp =0 To size
     me(lp)=Rnd(1000)
  Next
EndFunction Me()
  
  
  




This example would output.

  
  This Function doesn't Return anything
  I Exit late
  I Exit early
  42
  Deep Thought
  4.321
  



Top




 
Related Info: EndFunction | ExitFunction | Functions&Psub | Gosub | LIst | MakeArray | Psub | Type :
 


(c) Copyright 2002 - 2024 - Kevin Picone - PlayBASIC.com